#include "stream.h" 
#include <cstddef>
#include <cstdint>

//读固定长度的数据
int Stream::readFixSize(void* buffer, size_t length)
{
    size_t offset = 0; //偏移量（已经读出的字节数）
    int64_t left = length; //剩余要读的字节数

    while(left > 0)
    {
        int64_t len = read((char*)buffer + offset, left); //读取数据
        if (len <= 0)
        {
            return len;
        }
        offset += len;
        left -= len;
    }
    return length;
}

//读固定长度的数据
int Stream::readFixSize(ByteArray::ptr ba, size_t length)
{
    uint64_t left = length; //剩余要读的字节数
    while(left > 0)
    {
        int64_t len = read(ba, left); //读取数据
        if (len <= 0)
        {
            return len;
        }
        left -= len;
    }
    return length;
}

//写固定长度的数据
int Stream::writeFixSize(const void* buffer, size_t length)
{
    size_t offset = 0; //偏移量（已经写出的字节数）
    int64_t left = length; //剩余要写的字节数
    while(left > 0)
    {
        int64_t len = write((char*)buffer + offset, left); //写入数据
        if (len <= 0)
        {
            return len;
        }
        offset += len;
        left -= len;
    }
    return length;
}

//写固定长度的数据
int Stream::writeFixSize(ByteArray::ptr ba, size_t length)
{
    uint64_t left = length; //剩余要写的字节数
    while(left > 0)
    {
        int64_t len = write(ba, left); //写入数据
        if (len <= 0)
        {
            return len;
        }
        left -= len;
    }
    return length;
}